package com.future.bantang.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.future.bantang.R;
import com.future.bantang.activity.ShoppingListActivity;
import com.future.bantang.adapter.SubFieldListAdapter;
import com.future.bantang.constants.BanTang;
import com.future.bantang.entity.SubFieldEntity;
import com.future.bantang.utils.JsonUtils;
import com.future.bantang.utils.L;
import com.future.bantang.utils.NetUtils;
import com.future.bantang.view.BanTangListView;
import com.future.bantang.view.BanTangScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by Administrator on 16-1-13.
 */
public class SubFieldFragment extends BaseFragment {
    @ViewInject(R.id.lv_fragment_home_body_subfragment)
    private BanTangListView mListView;

    //listview数据适配器
    private SubFieldListAdapter mOthersAdapter;

    //接收上级Fragment传来的mBanTangSV
    private BanTangScrollView mBanTangSv;
    //上拉加载显示progress的
    private ImageView mIvProgress;
    //上拉加载的view的图片旋转动画
    private Animation mAnimProRotate;
    //上拉加载的显式的view
    private View mPulView;

    private List<SubFieldEntity.DataEntity> mSfDataList;

    @Subscribe(threadMode = ThreadMode.MainThread, sticky = true)
    public void receiveBanTangSv(HomeFragment.ScrollViewMsg msg) {
        mBanTangSv = msg.getT();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        L.d("lift_circle", "onCreate");

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        L.d("lift_circle","onCreateView");
        View view = inflater.inflate(R.layout.fragment_home_body_subfragment, null);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        L.d("lift_circle", "onViewCreated");

    }

    private float lastY = 0;

    @Override
    protected void initView(View view) {
        super.initView(view);
        //与上层fragment配合处理事件拦截问题
        mListView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mListView.getFirstVisiblePosition() == 0) {
                            if (mListView.getChildAt(0).getTop() >= 0) {
                                if (lastY == 0) {
                                    lastY = event.getRawY();
                                } else {
                                    float rawY = event.getRawY();
                                    if (rawY - lastY > 0) {
                                        mBanTangSv.setIsIntercept(true);
                                    } else {
                                        lastY = rawY;
                                    }
                                }
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        lastY = 0;
                        break;
                }
                return false;
            }
        });
        Bundle bundle = getArguments();
        this.scene = bundle.getInt("scene", -1);

        //设置listview不获取焦点，否则加载完数据listview会弹到整个屏幕
        mListView.setFocusable(false);
        mOthersAdapter = new SubFieldListAdapter(getActivity());
        mListView.setAdapter(mOthersAdapter);

        setListViewPullUpLoad();

        mSfDataList=new ArrayList<>();

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(getActivity(), ShoppingListActivity.class);
                intent.putExtra("id",dataEntities.get(position).getId());
                startActivity(intent);
            }
        });

    }

    private boolean isListViewToBottom = false;

    /**
     * 设置上拉加载
     */
    private void setListViewPullUpLoad() {
        //添加上拉加载的view
        mPulView = LayoutInflater.from(getActivity()).inflate(R.layout.view_pull_up_load, null);
        mListView.addFooterView(mPulView);
        mIvProgress = (ImageView) mPulView.findViewById(R.id.iv_pull_pu_load_progress);
        mAnimProRotate = AnimationUtils.loadAnimation(getActivity(), R.anim.pull_up_load_progress_rotate);
        mIvProgress.startAnimation(mAnimProRotate);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (isListViewToBottom && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    loadSubFieldDatas();
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                isListViewToBottom = (firstVisibleItem + visibleItemCount == totalItemCount );
            }
        });

    }

    private int scene;

    private int pageIndex = 0;

    private int pageSize = 20;

    @Override
    protected void loadDatas() {
        super.loadDatas();

        loadSubFieldDatas();

    }


    private List<SubFieldEntity.DataEntity> dataEntities;

    /**
     * 加载分栏内容
     */
    private void loadSubFieldDatas() {
        L.d("其他分栏加载数据");
        RequestParams requestParams = new NetUtils.RequestParamsBuilder()
                .addPostParameter(BanTang.CLIENT_ID_KEY, BanTang.CLIENT_ID_VALUE)
                .addPostParameter(BanTang.CLIENT_SECRET_KEY, BanTang.CLIENT_SECRET_VALUE)
                .addPostParameter(BanTang.SCENE_KEY, this.scene + "")
                .addPostParameter(BanTang.TYPE_KEY, BanTang.TYPE_VALUE)
                .addPostParameter(BanTang.PAGE, pageIndex + "")
                .addPostParameter(BanTang.PAGESIZE, pageSize + "")
                .build();
        NetUtils.loadSubFieldDatas(requestParams, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    SubFieldEntity subFieldEntity = JsonUtils
                            .perse(responseInfo.result, SubFieldEntity.class);
                    dataEntities = subFieldEntity.getData();
                    mOthersAdapter.addDatas(dataEntities, subFieldEntity.getTs());
                    mSfDataList.addAll(dataEntities);
                    pageIndex++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });

    }




    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        mListView.removeFooterView(mPulView);
        mListView=null;
        mOthersAdapter.clearDatas();
        mOthersAdapter=null;
        pageIndex=0;
        mSfDataList.clear();
        mSfDataList=null;
        L.d("lift_circle", "onDestroyView");

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        L.d("lift_circle", "onDestroy");

    }

    @Override
    public String toString() {
        return "SubFieldFragment---" + this.hashCode();
    }
}
